package biz

import (
	"errors"
	"io"
	"net"
	"time"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/jiushengTech/common/transport/socket"
	"transfer-service/internal/global"
)

type AntiCarTcpServer struct {
	*socket.TCPServer
}

type AntiCarUseCase struct {
	antiCarTcpServer *AntiCarTcpServer
	log              *log.Helper
}

func NewAntiCarUseCase(logger log.Logger,
	antiCarTcpServer *AntiCarTcpServer,
) *AntiCarUseCase {
	return &AntiCarUseCase{
		log:              log.NewHelper(log.With(logger, "module", "internal/biz/car")),
		antiCarTcpServer: antiCarTcpServer,
	}
}

// TransferData 接收并转发反制车数据（支持循环监听）
func (uc *AntiCarUseCase) TransferData() {
	for {
		tcpListener := uc.antiCarTcpServer.GetTcpListener()
		if tcpListener == nil {
			time.Sleep(time.Second)
			continue
		}

		tcpConn, err := tcpListener.AcceptTCP()
		if err != nil {
			uc.log.Errorf("tcp accept err: %v", err)
			continue
		}

		// 异步处理连接
		err = global.APOOL.Submit(func() {
			uc.handleTCPConnection(tcpConn)
		})
		if err != nil {
			uc.log.Errorf("submit task err: %v", err)
			_ = tcpConn.Close()
		}
	}
}

func (uc *AntiCarUseCase) handleTCPConnection(conn net.Conn) {
	defer conn.Close()

	clientAddr := conn.RemoteAddr().String()
	uc.log.Infof("收到连接: %s", clientAddr)

	data := make([]byte, 10240)

	for {
		n, err := conn.Read(data)
		if err != nil {
			if errors.As(err, &io.EOF) {
				uc.log.Infof("连接 %s 正常关闭", clientAddr)
			} else {
				var netErr net.Error
				if errors.As(err, &netErr) && netErr.Timeout() {
					uc.log.Warnf("连接 %s 读取超时，关闭连接", clientAddr)
				} else {
					uc.log.Errorf("读取连接 %s 出错: %v", clientAddr, err)
				}
			}
			return
		}

		// 广播数据
		send, err := uc.antiCarTcpServer.Broadcast(data[:n])
		if err != nil {
			uc.log.Errorf("反制车数据转发公安内网失败 %s: %v", clientAddr, err)
			continue
		}
		uc.log.Infof("反制车数据转发公安内网转发成功 %d 字节数据 来自 %s", send, clientAddr)
	}
}
